import {Injectable} from '@angular/core';
import {List} from '../../../domain/entities';
import {Subject} from 'rxjs';
import {LocalStorageService} from '../local-storage.service';
import {LISTS} from '../local-storage.namespace';

/**
 * 特定列表UUID
 */
type SpecialListUUID = 'today' | 'todo';

/**
 * 列表服务
 */
@Injectable({
  providedIn: 'root'
})
export class ListService {

  private current: List; // 当前列表
  private lists: List[] = []; // 所有列表

  currentUuid: SpecialListUUID | string = 'today'; // 默认为当天
  currentUuid$ = new Subject<string>();
  current$ = new Subject<List>();
  lists$ = new Subject<List[]>();

  constructor(
    private store: LocalStorageService
  ) {
  }

  // 广播
  private broadCast() {
    this.lists$.next(this.lists);
    this.current$.next(this.current);
    this.currentUuid$.next(this.currentUuid);
  }

  // 持久化
  private persist() {
    this.store.set(LISTS, this.lists);
  }

  // 通过 uuid 获取列表
  private getByUuid(uuid: string): List {
    return this.lists.find(l => l._id === uuid);
  }

  // 更新列表
  private update(list: List) {
    const index = this.lists.findIndex(l => l._id === list._id);
    if (index !== -1) {
      this.lists.splice(index, 1, list); // 要用splice, 不用 =
      this.persist();
      this.broadCast();
    }
  }

  /**
   * 获取当前列表 uuid
   */
  getCurrentListUuid(): SpecialListUUID | string {
    return this.currentUuid;
  }

  /**
   * 获取所有列表
   */
  getAll() {
    this.lists = this.store.getList<List>(LISTS);
    this.broadCast();
  }

  /**
   * 设置当前 uuid
   * @param uuid UUID
   */
  setCurrentUuid(uuid: string) {
    this.currentUuid = uuid;
    this.current = this.lists.find(l => l._id === uuid);
    this.broadCast();
  }

  /**
   * 添加列表
   * @param title 标题
   */
  add(title: string) {
    const newList = new List(title);
    this.lists.push(newList);
    this.currentUuid = newList._id;
    this.current = newList;

    this.broadCast();
    this.persist();
  }

  /**
   * 重命名
   * @param listUuid UUID
   * @param title 标题
   */
  rename(listUuid: string, title: string) {
    const list = this.getByUuid(listUuid);
    if (list) {
      list.title = title;
      this.update(list);
    }
  }

  /**
   * 删除
   * @param uuid UUID
   */
  delete(uuid: string) {
    const index = this.lists.findIndex(l => l._id === uuid);
    if (index !== -1) {
      this.lists.splice(index, 1);
      this.currentUuid = this.lists.length
        ? this.lists[this.lists.length - 1]._id
        : this.currentUuid === 'today'
          ? 'today'
          : 'todo';

      this.broadCast();
      this.persist();
    }
  }
}
